//
//  WKChatViewController.m
//  Walk
//
//  Created by cesh on 16/9/6.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKChatViewController.h"
#import "WKCardViewController.h"
#import "WKReportViewController.h"
#import "WKBubbleViewController.h"
#import "WKMeTableViewCell.h"
#import "WKYouTableViewCell.h"
#import "WKSingleViewController.h"
#import "EMCDDeviceManager.h"
#import "WKAudioTool.h"
#import "WKAnnotation.h"
#import "WKMultipleViewController.h"

#import <MapKit/MapKit.h>
#import <SVProgressHUD.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <UIImageView+WebCache.h>
#import <UIImage+MultiFormat.h>
#import <EMSDK.h>

@interface WKChatViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate,EMChatManagerDelegate, EMChatroomManagerDelegate, UITextFieldDelegate, WKYouTableViewCellDelegate, WKMeTableViewCellDelegate, AMapLocationManagerDelegate, MKMapViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, GoChatProtocal>

@property (weak, nonatomic) IBOutlet UIImageView *backImg;
@property (weak, nonatomic) IBOutlet UIImageView *moreImg;
@property (weak, nonatomic) IBOutlet UITableView *messagesTableView;

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewContraint;

@property (weak, nonatomic) IBOutlet UILabel *recruitLbl;
@property (weak, nonatomic) IBOutlet UIImageView *recruitImg;
@property (weak, nonatomic) IBOutlet UIView *topFrogImg;

@property (strong, nonatomic) UITapGestureRecognizer *stopRecruitTap;
@property (strong, nonatomic) UITapGestureRecognizer *goCardVC;
//语音界面的底部view
@property (strong, nonatomic) UIView *recordBgView;
@property (strong, nonatomic) UILabel *recordLabel;
@property (strong, nonatomic) UIButton *speak;

/** 表格的数据源 */
@property (strong, nonatomic) NSMutableArray <EMMessage *> *dataSouces;

/** 聊天cell的工具(计算cell的高度) */
@property (strong, nonatomic) WKYouTableViewCell *chatCellToolYou;
@property (strong, nonatomic) WKMeTableViewCell *chatCellToolMe;

@property (weak, nonatomic) IBOutlet UITextField *textField;

@property (weak, nonatomic) IBOutlet UIButton *recordBtn;
//环信聊天室
@property (strong, nonatomic) EMChatroom *chatroom;

@property (copy, nonatomic) NSString *continueAddStatus;

//聊天室的id
@property (strong, nonatomic) NSString *chatroom_id;
//事件id
@property (strong, nonatomic) NSString *event_id;
/**
 *  定位相关
 */
@property (strong, nonatomic) AMapLocationManager *locationManager;
@property (assign, nonatomic) CLLocation *location;

@property (strong, nonatomic) MKMapView *mapView;
@property (strong, nonatomic) CLGeocoder *geoC;

/**
 *  图片浏览器
 */

@property (strong, nonatomic) NSMutableArray *photos;

@property (strong, nonatomic) AFHTTPSessionManager *manager;

@property (strong, nonatomic) NSTimer *countDownTimer;

@property (strong, nonatomic) UIAlertController *alert;


@property (strong, nonatomic) NSURLSessionDataTask *chatroomChange;
@end

@implementation WKChatViewController
#pragma mark - 懒加载

- (WKYouTableViewCell *)chatCellToolYou{
    if (!_chatCellToolYou) {
        _chatCellToolYou = [[[NSBundle mainBundle]loadNibNamed:@"WKYouTableViewCell" owner:nil options:nil]lastObject];
    }
    
    return _chatCellToolYou;
}
- (WKMeTableViewCell *)chatCellToolMe{
    if (!_chatCellToolMe) {
        _chatCellToolMe = [[[NSBundle mainBundle]loadNibNamed:@"WKMeTableViewCell" owner:nil options:nil]lastObject];
    }
    
    return _chatCellToolMe;
}
- (NSMutableArray *)dataSouces{
    if (_dataSouces == nil) {
        _dataSouces = [NSMutableArray array];
    }
    return _dataSouces;
}

- (void)resignKeyboard {
    [self.textField resignFirstResponder];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.textField.delegate = self;
    
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignKeyboard)]];
    
    self.backImg.userInteractionEnabled = YES;
    
    self.moreImg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapOnMoreImg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(more)];
    [self.moreImg addGestureRecognizer:tapOnMoreImg];
    
    self.messagesTableView.dataSource = self;
    self.messagesTableView.delegate = self;

    self.messagesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.textField.delegate = self;
    //注册聊天室回调
    [[EMClient sharedClient].roomManager addDelegate:self delegateQueue:nil];
    
    //获取聊天室的的相关数据
    
    
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    
    [mgr POST:[NSString stringWithFormat:@"%@Msg/msgInfo",URL] parameters:@{@"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"]} progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取聊天时信息%@", responseObject);
        NSString *state = responseObject[@"state"];
        if ([state isEqualToString:@"FAIL"]) {
            [self backToBubble];
            return;
        }
        
        [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"data"][@"event_id"] forKey:@"eventID"];
        NSDictionary *chatroom = responseObject[@"data"];
        [[NSUserDefaults standardUserDefaults]setObject:chatroom forKey:@"chatroom"];
        NSLog(@"聊天室数据 %@", chatroom);
        
        self.chatroom_id = chatroom[@"hx_id"];
        self.event_id = chatroom[@"event_id"];
        //根据能否继续招募 设置顶上的按钮
        NSString *continueAddStatus = chatroom[@"continueAddStatus"];
        self.continueAddStatus = continueAddStatus;
        // 字段为0 不能招募
        if ([continueAddStatus isEqualToString:@"0"]) {
            self.recruitImg.image = [UIImage imageNamed:@"add_disable"];
            self.recruitLbl.hidden = YES;
            self.topFrogImg.userInteractionEnabled = YES;
            //青蛙按钮添加一个提示框，提示用户没有继续招募的权限
            UITapGestureRecognizer *topFrogCanNotRecruitMore = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(remindCanNotRecruitMore)];
            [self.topFrogImg addGestureRecognizer:topFrogCanNotRecruitMore];
            
            //返回键始终返回气泡界面
            UITapGestureRecognizer *goBubbleVC = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backToBubble)];
            [self.backImg addGestureRecognizer:goBubbleVC];
        }
        //字段为1 按钮设为停止招募
        else if ([continueAddStatus isEqualToString:@"1"]){
            self.topFrogImg.userInteractionEnabled = YES;
            UITapGestureRecognizer *tapOnTopFrog = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(stopRecruit)];
            self.recruitLbl.text = @"停止招募";
            self.stopRecruitTap = tapOnTopFrog;
            [self.topFrogImg addGestureRecognizer:tapOnTopFrog];
            
            //按钮为停止招募，事件状态是招募中，返回键返回卡片界面
            UITapGestureRecognizer *goCardVC = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backToCard)];
            self.goCardVC = goCardVC;
            [self.backImg addGestureRecognizer:goCardVC];
        }
        //字段为2 按钮设为继续招募
        else if ([continueAddStatus isEqualToString:@"2"]){
            self.topFrogImg.userInteractionEnabled = YES;
            UITapGestureRecognizer *tapOnTopFrog = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(recruitMore)];
            [self.topFrogImg addGestureRecognizer:tapOnTopFrog];
            ////按钮为继续招募，事件状态为停止招募，返回键返回气泡界面
            UITapGestureRecognizer *goBubbleVC = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backToBubble)];
            [self.backImg addGestureRecognizer:goBubbleVC];
        }
        
        //进入聊天室
        EMError *error = nil;
        
        [[EMClient sharedClient].roomManager joinChatroom:self.chatroom_id error:&error];
        
        //记录聊天室id，便于持久化获取聊天室的本地记录
        [[NSUserDefaults standardUserDefaults]setObject:self.chatroom_id forKey:@"chatroom_id"];
        
        //设置chatManager代理
        [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
        
        //监听聊天室的改变
        [self chatroomChanged];
        
        //解析持久化的聊天信息
        [self loadChatData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取聊天时信息 失败 %@", error);
    }];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)chatroomChanged {
    self.manager = nil;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    self.manager = manager;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = MAXFLOAT;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"RoomID" : self.chatroom_id,
                           @"continueAddStatus" : self.continueAddStatus
                           };
    NSLog(@"聊天室改变 发送数据%@",dict);
    self.chatroomChange = [manager POST:[NSString stringWithFormat:@"%@Frog/isChangeRoom", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"聊天室改变 %@",responseObject);
        //
        NSString *fail = responseObject[@"state"];
        if ([fail isEqualToString:@"FAIL"]) {
            [self backToBubble];
            return;
        }
        
        //如果聊天室发生了改变，则进行如下操作
        NSString *newChatroom_id = responseObject[@"data"][@"hx_id"];
        self.continueAddStatus = responseObject[@"data"][@"continueAddStatus"];
        if (![newChatroom_id isEqualToString:self.chatroom_id]) {
            //退出原来的聊天室
            EMError *error = nil;
            [[EMClient sharedClient].roomManager leaveChatroom:self.chatroom_id error:&error];
            
            if (!error) {
                NSLog(@"退出原聊天室%@成功", self.chatroom_id);
            }
            else {
                NSLog(@"退出原聊天室%@失败", self.chatroom_id);
            }
            
            //进入新的聊天室
            self.chatroom_id = responseObject[@"data"][@"hx_id"];
            
            EMError *errorNew = nil;
            [[EMClient sharedClient].roomManager joinChatroom:self.chatroom_id error:&errorNew];
            if (!errorNew) {
                NSLog(@"进入新聊天室%@成功", self.chatroom_id);
            }
            else {
                NSLog(@"进入新聊天室%@失败", self.chatroom_id);
            }
        }
        // 根据返回的能否继续招募字段更改顶部青蛙按钮
        // 字段为0 不能招募
        if ([self.continueAddStatus isEqualToString:@"0"]) {
            self.recruitImg.image = [UIImage imageNamed:@"add_disable"];
            self.recruitLbl.hidden = YES;
            self.topFrogImg.userInteractionEnabled = YES;
            //青蛙按钮添加一个提示框，提示用户没有继续招募的权限
            UITapGestureRecognizer *topFrogCanNotRecruitMore = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(remindCanNotRecruitMore)];
            [self.topFrogImg addGestureRecognizer:topFrogCanNotRecruitMore];
            
            //返回键始终返回气泡界面
            UITapGestureRecognizer *goBubbleVC = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backToBubble)];
            [self.backImg addGestureRecognizer:goBubbleVC];
        }
        //字段为1 按钮设为停止招募
        else if ([self.continueAddStatus isEqualToString:@"1"]){
            self.topFrogImg.userInteractionEnabled = YES;
            UITapGestureRecognizer *tapOnTopFrog = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(stopRecruit)];
            self.recruitLbl.text = @"停止招募";
            self.stopRecruitTap = tapOnTopFrog;
            [self.topFrogImg addGestureRecognizer:tapOnTopFrog];
            
            //按钮为停止招募，事件状态是招募中，返回键返回卡片界面
            UITapGestureRecognizer *goCardVC = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backToCard)];
            self.goCardVC = goCardVC;
            [self.backImg addGestureRecognizer:goCardVC];
        }
        //字段为2 按钮设为继续招募
        else if ([self.continueAddStatus isEqualToString:@"2"]){
            self.topFrogImg.userInteractionEnabled = YES;
            UITapGestureRecognizer *tapOnTopFrog = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(recruitMore)];
            [self.topFrogImg addGestureRecognizer:tapOnTopFrog];
            ////按钮为继续招募，事件状态为停止招募，返回键返回气泡界面
            UITapGestureRecognizer *goBubbleVC = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backToBubble)];
            [self.backImg addGestureRecognizer:goBubbleVC];
        }
        
        //重新挂起该长链接, 等待下一次聊天室改变
        [self chatroomChanged];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"聊天室改变失败 %@",error);
    }];
}
//弹出提示框提示用户没有招募更多的权限
- (void)remindCanNotRecruitMore {
    [WKPopView showWithType:PopViewTypeCanNotRecruitMore];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WKPopView dismiss];
    });
}

- (void)stopRecruit {
    NSLog(@"停止招募");
//    self.continueAddStatus = @"2";
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"],
                           @"type" : @"2"
                           };
    [mgr POST:[NSString stringWithFormat:@"%@Frog/handleEvenet", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"停止招募 %@",responseObject);
        [WKPopView showWithType:PopViewTypeQuitRecruit];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
            self.recruitLbl.text = @"继续招募";
            //移除原来返回按钮的回到卡片界面
            [self.backImg removeGestureRecognizer:self.goCardVC];
            //添加返回按钮的回到气泡界面
            UITapGestureRecognizer *goBubbleVC = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backToBubble)];
            [self.backImg addGestureRecognizer:goBubbleVC];
            //移除原来青蛙按钮的停止招募事件
            [self.topFrogImg removeGestureRecognizer:self.stopRecruitTap];
            //添加青蛙按钮的招募更多事件
            UITapGestureRecognizer *tapOnTopFrog = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(recruitMore)];
            [self.topFrogImg addGestureRecognizer:tapOnTopFrog];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"停止招募 失败 %@", error);
    }];
}

- (void)recruitMore {
    NSLog(@"继续招募");
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                      @"text/html",
                                                      @"image/jpeg",
                                                      @"image/png",
                                                      @"application/octet-stream",
                                                      @"text/json",
                                                      nil];
    NSDictionary *dict = @{
                            @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                            @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"],
                            @"type" : @"1"
                            };
    [mgr POST:[NSString stringWithFormat:@"%@Frog/handleEvenet", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"继续招募 %@",responseObject);
        
        //如果收到的state是失败，则提示用户
        NSString *state = responseObject[@"state"];
        if ([state isEqualToString:@"FAIL"]) {
            NSString *description = responseObject[@"data"];
            [SVProgressHUD showWithStatus:description];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        else {
            WKCardViewController *cardVC = [[WKCardViewController alloc]init];
            CATransition *anim = [CATransition animation];
            anim.type = @"rippleEffect";
            anim.duration = 1.0;
            [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
            [self presentViewController:cardVC animated:NO completion:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"继续招募 失败 %@", error);
    }];
}

- (void)loadChatData {
    NSDictionary *chatroom = [[NSUserDefaults standardUserDefaults]objectForKey:@"chatroom"];
    NSString *chatroom_id = chatroom[@"hx_id"];
    // 获取与当前用户的会话对象
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:chatroom_id type:EMConversationTypeChatRoom createIfNotExist:YES];
    
    
    // 把所有的消息都加载
    NSArray *messages = [conversation loadMoreMessagesFromId:nil limit:100 direction:EMMessageSearchDirectionUp];
    
    // 遍历消息
    for (EMMessage *message in messages) {
        [self.dataSouces addObject:message];
    }
    
    
    [self.messagesTableView reloadData];
    
    //一进入就tableView划到底端
    if (self.dataSouces.count != 0) {
        [self.messagesTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSouces.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

//键盘弹出和退出的时候，顶部View做相应调整
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //1.获取键盘的高度
    CGRect kbEndFrm =  [aNotification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat kbHeight = kbEndFrm.size.height - 41;
    
    //2.更改顶部view的底部约束为键盘的高度
    self.bottomViewContraint.constant = kbHeight;
    // 添加动画
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{

    self.bottomViewContraint.constant = 0;
    // 添加动画
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - 聊天室代理
//有用户进入聊天室时候回调
- (void)didReceiveUserJoinedChatroom:(EMChatroom *)aChatroom
                            username:(NSString *)aUsername {
    
    NSLog(@"用户%@加入了聊天室%@", aUsername, aChatroom.chatroomId);
}

- (void)didReceiveUserLeavedChatroom:(EMChatroom *)aChatroom
                            username:(NSString *)aUsername {
    NSLog(@"用户%@离开了聊天室%@", aUsername, aChatroom.chatroomId);
}

- (void)didReceiveKickedFromChatroom:(EMChatroom *)aChatroom
                              reason:(EMChatroomBeKickedReason)aReason {
    NSLog(@"用户被踢出了聊天室%@ ，原因:%i", aChatroom.chatroomId, aReason);
}

- (void)beKickedOutFromChatroom:(EMChatroom *)chatroom {
     NSLog(@"用户被踢出了聊天室%@", chatroom.chatroomId);
}

#pragma mark - 收到消息
-(void)didReceiveMessages:(NSArray *)aMessages{
    NSDictionary *chatroom = [[NSUserDefaults standardUserDefaults]objectForKey:@"chatroom"];
    NSString *chatroom_id = chatroom[@"hx_id"];
    for (EMMessage *message in aMessages) {
        
        message.conversationId = chatroom_id;
        //设置消息类型为：接受的消息
        message.direction = EMMessageDirectionReceive;
        [self.dataSouces addObject:message];
        EMMessageBody *body = message.body;
        //收到文本消息
        if ([body isKindOfClass:[EMTextMessageBody class]]) {

        }
        //收到图片消息
        else if ([body isKindOfClass:[EMImageMessageBody class]]) {
            EMImageMessageBody *body = (EMImageMessageBody *)message.body;
            BOOL isImgExit = [[NSFileManager defaultManager] fileExistsAtPath:body.thumbnailLocalPath];
            UIImageView *imageV = [[UIImageView alloc]init];
            if (isImgExit) {
                imageV.image = [UIImage imageWithContentsOfFile:body.thumbnailLocalPath];

            }else{
                //从网络加载图片
                [imageV sd_setImageWithURL:[NSURL URLWithString:body.thumbnailRemotePath] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                }];
            }
        }
        [self.messagesTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.dataSouces.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        
        [self.messagesTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSouces.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
}
#pragma mark - 发送信息
//发送消息的公共方法
-(void)sendChatMesage:(EMMessageBody *)body{
    
    NSString *from = [[EMClient sharedClient] currentUsername];
    NSDictionary *chatroom = [[NSUserDefaults standardUserDefaults]objectForKey:@"chatroom"];
    NSString *chatroom_id = chatroom[@"hx_id"];
    // 生成message
    EMMessage *message = [[EMMessage alloc] initWithConversationID:chatroom_id from:from to:self.chatroom_id body:body ext:nil];
    
    message.direction = EMMessageDirectionSend;//设置为发送的消息
    message.chatType = EMChatTypeChatRoom;// 设置为聊天室消息
    
    //加入datasource中
    [self.dataSouces addObject:message];
    // 3.发送聊天消息
    [[EMClient sharedClient].chatManager asyncSendMessage:message progress:NULL completion:^(EMMessage *message, EMError *error) {
        if (!error) {
            NSLog(@"消息发送成功");
            //如果是文本消息
            if ([message.body isKindOfClass:[EMTextMessageBody class]]) {

            }
            //如果是图片消息
            else if ([message.body isKindOfClass:[EMImageMessageBody class]]) {
                EMImageMessageBody *body = (EMImageMessageBody *)message.body;
                BOOL isImgExit = [[NSFileManager defaultManager] fileExistsAtPath:body.thumbnailLocalPath];
                UIImageView *imageV = [[UIImageView alloc]init];
                if (isImgExit) {
                    imageV.image = [UIImage imageWithContentsOfFile:body.thumbnailLocalPath];
                }else{
                    //从网络加载图片
                    [imageV sd_setImageWithURL:[NSURL URLWithString:body.thumbnailRemotePath] placeholderImage:[UIImage imageNamed:@"default_head"]];
                }
            }
        }else{
            NSLog(@"消息发送失败 %@",error.errorDescription);
        }
    }];

    // 4.读取最新的一个cell

    [self.messagesTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.dataSouces.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [self.messagesTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSouces.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}
//文字消息
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //拦截为空的情况
    if ([textField.text length] > 0) {
        //发送消息
        EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:textField.text];
        
        textField.text = @"";
        
        [self sendChatMesage:body];
    }
    return YES;
}

//语音消息
-(void)sendVoiceMessage:(NSString *)recordPath duration:(NSInteger)duration{
    //创建语音的消息体
    EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithLocalPath:recordPath displayName:@"audio"];
    body.duration = (int)duration;
    [self sendChatMesage:body];
}
//图片消息
-(void)sendImageMessage:(UIImage *)img{
    // 创建图片的消息体
    NSData *data = UIImageJPEGRepresentation(img, 0.5);//原始图片
    NSData *thumbnailData = UIImageJPEGRepresentation(img, 0.25);//缩略图
    
    EMImageMessageBody *imgBody = [[EMImageMessageBody alloc] initWithData:data thumbnailData:thumbnailData];
    
    [self sendChatMesage:imgBody];
}
#pragma mark - 顶部两个按钮

- (void)backToBubble {
    [self.textField resignFirstResponder];
    
    WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
    CATransition *anim = [CATransition animation];
    anim.type = @"rippleEffect";
    anim.duration = 1.0;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
    
    [UIApplication sharedApplication].keyWindow.rootViewController = bubbleVC;
}

- (void)backToCard {
    [self.textField resignFirstResponder];
    
    WKCardViewController *cardVC = [[WKCardViewController alloc]init];
    CATransition *anim = [CATransition animation];
    anim.type = @"rippleEffect";
    anim.duration = 1.0;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
    
    [UIApplication sharedApplication].keyWindow.rootViewController = cardVC;
}

- (void)alertCountDown {
    //对话框消失的倒计时
    NSDictionary *chatroom = [[NSUserDefaults standardUserDefaults]objectForKey:@"chatroom"];
    NSString *expireTime = chatroom[@"expireTime"];
    NSInteger countDown = [expireTime integerValue] - [[NSDate date]timeIntervalSince1970];
    [self.alert setMessage:[NSString stringWithFormat:@"%02li:%02li:%02li", countDown / 3600, (countDown / 60) % 60, countDown % 60]];
}

- (void)more {
    [self.textField resignFirstResponder];
    //对话框消失的倒计时
    NSDictionary *chatroom = [[NSUserDefaults standardUserDefaults]objectForKey:@"chatroom"];
    NSString *expireTime = chatroom[@"expireTime"];
    NSInteger countDown = [expireTime integerValue] - [[NSDate date]timeIntervalSince1970];
    
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"对话框消失倒计时" message:[NSString stringWithFormat:@"%02li:%02li:%02li", countDown / 3600, (countDown / 60) % 60, countDown % 60] preferredStyle:UIAlertControllerStyleActionSheet];
    self.alert = alert;
    self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(alertCountDown) userInfo:nil repeats:YES];
    
    UIAlertAction *check = [UIAlertAction actionWithTitle:@"查看人员" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //弹出多人界面
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
        NSDictionary *dict = @{
                               @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                               @"eventID" : self.event_id,
                               @"page" : @"1",
                               @"pagesize" : @"10"
                               };
        NSLog(@"%@", dict);
        
        [mgr POST:[NSString stringWithFormat:@"%@Frog/getEventMoreUsers", URL] parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"个人详情 %@",responseObject);
            WKMultipleViewController *multipleVC = [[WKMultipleViewController alloc]init];
            multipleVC.hideBottomBtns = YES;
            NSArray *others = responseObject[@"data"];
            multipleVC.count = others.count;
            [self presentViewController:multipleVC animated:NO completion:^{
                //创建一个白色的view遮住底部的按钮
                UIView *bottomCoverView = [[UIView alloc]initWithFrame:CGRectMake(0, screenH - 46, screenW, 46)];
                bottomCoverView.backgroundColor = [UIColor colorWithRed:0xf0 / 255.0 green:0xf0 / 255.0 blue:0xf0 / 255.0 alpha:1.0];
                [multipleVC.view addSubview:bottomCoverView];
                multipleVC.data = responseObject[@"data"];
            }];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"个人详情失败 %@", error);
        }];
    }];
    UIAlertAction *report = [UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //弹出举报界面
        WKReportViewController *reportVC = [[WKReportViewController alloc]init];
        reportVC.reportType = ReportTypeEvent;
        reportVC.event_id = self.event_id;
        [self presentViewController:reportVC animated:YES completion:nil];
    }];
    UIAlertAction *complete = [UIAlertAction actionWithTitle:@"完成活动" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //完成活动
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
        NSDictionary *dict = @{
                               @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                               @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"],
                               @"type" : @"4"
                               };
        [mgr POST:[NSString stringWithFormat:@"%@Frog/handleEvenet", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"完成活动 成功 %@",responseObject);
            [self.chatroomChange cancel];
            
            //停止监控聊天室变化情况
            self.manager = nil;
            //退出环信聊天室
            EMError *error = nil;
            [[EMClient sharedClient].roomManager leaveChatroom:self.chatroom_id error:&error];
            if (!error) {
                NSLog(@"退出环信聊天室 成功");
            }
            else {
                NSLog(@"退出环信聊天室 失败");
            }
            
            WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
            CATransition *anim = [CATransition animation];
            anim.type = @"rippleEffect";
            anim.duration = 1.0;
            [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
            [self presentViewController:bubbleVC animated:NO completion:nil];
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL otherUsersHave=[[NSFileManager defaultManager] fileExistsAtPath:otherUsersNameHead];
            if (!otherUsersHave) {
                NSLog(@"otherUsers no  have");
                return ;
            }else {
                NSLog(@"userimg have");
                BOOL userimgDele= [fileManager removeItemAtPath:otherUsersNameHead error:nil];
                if (userimgDele) {
                    NSLog(@"otherUsers Dele success");
                }else {
                    NSLog(@"otherUsers Dele fail");
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"退出活动 失败 %@", error);
        }];
    }];
    
    UIAlertAction *resign = [UIAlertAction actionWithTitle:@"退出聊天" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        WKPopView *popV = [WKPopView showWithType:PopViewTypeQuitChat];
        popV.delegate = self;
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.countDownTimer invalidate];
        self.countDownTimer = nil;
    }];
    [alert addAction:check];
    [alert addAction:report];
    [alert addAction:resign];
    [alert addAction:complete];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - PopView的代理方法
- (void)quitChat {
    [WKPopView dismiss];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"myEventID" : [[NSUserDefaults standardUserDefaults]valueForKey:@"eventID"],
                           @"type" : @"3"
                           };
    [mgr POST:[NSString stringWithFormat:@"%@Frog/handleEvenet", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"退出活动 %@",responseObject);
        
        [self.chatroomChange cancel];
        //停止监控聊天室变化情况
        self.manager = nil;
        //退出环信聊天室
        EMError *error = nil;
        [[EMClient sharedClient].roomManager leaveChatroom:self.chatroom_id error:&error];
        if (!error) {
            NSLog(@"退出环信聊天室 成功");
        }
        else {
            NSLog(@"退出环信聊天室 失败");
        }
        
        WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
        CATransition *anim = [CATransition animation];
        anim.type = @"rippleEffect";
        anim.duration = 1.0;
        [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
        [self presentViewController:bubbleVC animated:NO completion:nil];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL otherUsersHave=[[NSFileManager defaultManager] fileExistsAtPath:otherUsersNameHead];
        if (!otherUsersHave) {
            NSLog(@"otherUsers no  have");
            return ;
        }else {
            NSLog(@"userimg have");
            BOOL userimgDele= [fileManager removeItemAtPath:otherUsersNameHead error:nil];
            if (userimgDele) {
                NSLog(@"otherUsers Dele success");
            }else {
                NSLog(@"otherUsers Dele fail");
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"退出活动 失败 %@", error);
    }];
}

- (void)cancelQuitChat {
    [WKPopView dismiss];
}

#pragma mark - 代理方法
//点击头像推出单人页面
- (void)youTableViewCell:(WKYouTableViewCell *)youTableViewCell popSingleVC:(WKSingleViewController *)singleVC {
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"userID" : youTableViewCell.userID,
                           };

    [mgr GET:[NSString stringWithFormat:@"%@Frog/getUserInfo", URL] parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"个人详情 %@",responseObject);
        //根据单人或多人卡片弹出不同的控制器
        WKSingleViewController *singleVC = [[WKSingleViewController alloc]init];
        singleVC.isSuperMultiple = NO;
        singleVC.likeBtn.userInteractionEnabled = NO;
        singleVC.dislikeBtn.userInteractionEnabled = NO;
        [self presentViewController:singleVC animated:NO completion:^{
            //创建一个白色的view遮住底部的按钮
            UIView *bottomCoverView = [[UIView alloc]initWithFrame:CGRectMake(0, screenH - 46, screenW, 46)];
            bottomCoverView.backgroundColor = [UIColor colorWithRed:0xf0 / 255.0 green:0xf0 / 255.0 blue:0xf0 / 255.0 alpha:1.0];
            [singleVC.view addSubview:bottomCoverView];
        }];
        singleVC.data = responseObject[@"data"];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"个人详情失败 %@", error);
    }];
}
- (void)meTableViewCell:(WKMeTableViewCell *)meTableViewCell popSingleVC:(WKSingleViewController *)singleVC {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"userID" : meTableViewCell.userID,
                           };
    
    [mgr GET:[NSString stringWithFormat:@"%@Frog/getUserInfo", URL] parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"个人详情 %@",responseObject);
        //根据单人或多人卡片弹出不同的控制器
        
        WKSingleViewController *singleVC = [[WKSingleViewController alloc]init];
        singleVC.isSuperMultiple = NO;
        singleVC.likeBtn.enabled = NO;
        singleVC.dislikeBtn.enabled = NO;
        [self presentViewController:singleVC animated:NO completion:^{
            //创建一个白色的view遮住底部的按钮
            UIView *bottomCoverView = [[UIView alloc]initWithFrame:CGRectMake(0, screenH - 46, screenW, 46)];
            bottomCoverView.backgroundColor = [UIColor colorWithRed:0xf0 / 255.0 green:0xf0 / 255.0 blue:0xf0 / 255.0 alpha:1.0];
            [singleVC.view addSubview:bottomCoverView];
        }];
        singleVC.data = responseObject[@"data"];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"个人详情失败 %@", error);
    }];
}

#pragma mark - table view data source

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EMMessage *message = self.dataSouces[indexPath.row];
    //如果是我发的信息
    if (message.direction == EMMessageDirectionSend) {
        NSLog(@"me from:%@ to:%@", message.from, message.to);
//        WKMeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"me"];
//        if (cell == nil) {
//            cell = [[WKMeTableViewCell alloc]init];
//        }
        WKMeTableViewCell *cell = (WKMeTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"WKMeTableViewCell" owner:nil options:nil]lastObject];
        }
        
        cell.delegate = self;
        cell.message = message;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        //根据message的不同种类实现不同的cell
        //1.文本消息
        cell.message = message;
        if ([message.body isKindOfClass:[EMTextMessageBody class]]) {
        }
        //2.语音信息
        else if ([message.body isKindOfClass:[EMVoiceMessageBody class]]) {
            EMVoiceMessageBody *body = (EMVoiceMessageBody *)message.body;
            cell.audioSeconds = body.duration;
            cell.messageType = MessageTypeAudio;
        }
        //3.图片信息
        else if ([message.body isKindOfClass:[EMImageMessageBody class]]) {
            cell.message = message;
            cell.messageType = MessageTypePicture;
        }
        return cell;
    }
    //对方发的信息
    else {
        NSLog(@"you from:%@ to:%@", message.from, message.to);
//        WKYouTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"you"];
//        if (cell == nil) {
//            cell = [[WKYouTableViewCell alloc]init];
//        }
        WKYouTableViewCell *cell = (WKYouTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"WKYouTableViewCell" owner:nil options:nil]lastObject];
        }
        
        cell.delegate = self;
        cell.message = message;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        
        //根据message的不同种类实现不同的cell
        //1.文本消息
        if ([message.body isKindOfClass:[EMTextMessageBody class]]) {
        }
        //2.语音信息
        else if ([message.body isKindOfClass:[EMVoiceMessageBody class]]) {
            EMVoiceMessageBody *body = (EMVoiceMessageBody *)message.body;
            cell.audioSeconds = body.duration;
            cell.messageType = MessageTypeAudio;
        }
        //3.图片信息
        else if ([message.body isKindOfClass:[EMImageMessageBody class]]) {
            cell.message = message;
            cell.messageType = MessageTypePicture;
        }
        
        return cell;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSouces.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    EMMessage *message = self.dataSouces[indexPath.row];
    if (message.direction == EMMessageDirectionSend) {
        [self.chatCellToolMe setMessage:message];
        return [self.chatCellToolMe cellHeight];
    }
    else {
        [self.chatCellToolYou setMessage:message];
        return [self.chatCellToolYou cellHeight];
    }
}

#pragma mark - 底部的按钮

#pragma mark - 录音相关

//录音按钮的点击事件
- (IBAction)recordBtn:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    if(sender.selected == YES){
        UIView *recordBgView = [[UIView alloc]init];
        recordBgView.backgroundColor = [UIColor whiteColor];
        recordBgView.size = CGSizeMake(screenW, 215);
        recordBgView.center = CGPointMake(screenW * 0.5, screenH - recordBgView.height * 0.5);
        
        UILabel *recordLabel = [[UILabel alloc]init];
        recordLabel.text = @"按住说话";
        recordLabel.font = [UIFont systemFontOfSize:14];
        recordLabel.textColor = [UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0];
        [recordLabel sizeToFit];
        recordLabel.center = CGPointMake(screenW * 0.5, 30 + recordLabel.height * 0.5);
        self.recordLabel = recordLabel;
        [recordBgView addSubview:recordLabel];
        
        UIButton *speak = [UIButton buttonWithType:UIButtonTypeCustom];
        [speak setBackgroundImage:[UIImage imageNamed:@"speak"] forState:UIControlStateNormal];
        [speak sizeToFit];
        speak.center = CGPointMake(screenW * 0.5, recordLabel.bottom + 13 + speak.height * 0.5);
        self.speak = speak;
        [recordBgView addSubview:speak];
        self.recordBgView = recordBgView;
        
        //给按钮添加点击事件
        [speak addTarget:self action:@selector(speakTouchDown:) forControlEvents:UIControlEventTouchDown];
        [speak addTarget:self action:@selector(speakTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [speak addTarget:self action:@selector(speakTouchUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
        [self.view addSubview:recordBgView];
        //底部view上弹
        self.bottomViewContraint.constant = 217;
        
        //给view添加点击就退出录音view的事件
        UITapGestureRecognizer *tapOnBg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignRecordView)];
        [self.view addGestureRecognizer:tapOnBg];
        [self.view layoutIfNeeded];
        
    }
    else {
        self.bottomViewContraint.constant = 0;
        [UIView animateWithDuration:0.25 animations:^{
            [self.view layoutIfNeeded];
        }];
        [self.recordBgView removeFromSuperview];
    }
}

- (void)resignRecordView {
    self.recordBtn.selected = !self.recordBtn.isSelected;
    self.bottomViewContraint.constant = 0;
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    [self.recordBgView removeFromSuperview];
}

//录音按钮按下去
- (void)speakTouchDown:(UIButton *)speak {
    [speak setBackgroundImage:[UIImage imageNamed:@"speaking"] forState:UIControlStateNormal];
    //手指拖动到录音按钮的外面
    [speak addTarget:self action:@selector(moveOuside:) forControlEvents:UIControlEventTouchDragOutside];
    [self.recordLabel setText:@"上滑取消"];
    [self.recordLabel setTextColor:[UIColor colorWithRed:0x27 / 255.0 green:0x88 / 255.0 blue:0xff / 255.0 alpha:1.0]];
    //开始录音
    NSLog(@"开始录音");
    
    //1.生成录音文件的名字
    int x = arc4random() % 100000;
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
    
    //2.开始录音
    [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error)
     {
         if (!error) {
             NSLog(@"开始录音成功");
         }else{
             NSLog(@"开始录音失败");
         }
     }];
}
//手指在录音按钮内部松开
- (void)speakTouchUpInside:(UIButton *)speak {
    NSLog(@"发送录音");
    [speak setBackgroundImage:[UIImage imageNamed:@"speak"] forState:UIControlStateNormal];
    [self.recordLabel setText:@"按住说话"];
    [self.recordLabel setTextColor:[UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0]];
    
    //发送录音
    [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
        NSLog(@"录音文件路径 %@",recordPath);
        NSLog(@"录音时间 %zd",aDuration);
        if (!error) {
            [self sendVoiceMessage:recordPath duration:aDuration];
        }
        
    }];

}
//手指拖动到录音按钮的外面
- (void)moveOuside:(UIButton *)speak {
    //添加手指拖回按钮的操作
     [speak addTarget:self action:@selector(moveInside:) forControlEvents:UIControlEventTouchDragInside];
    
    [speak setBackgroundImage:[UIImage imageNamed:@"speaking_cancel"] forState:UIControlStateNormal];
    [self.recordLabel setText:@"松开取消"];
    [self.recordLabel setTextColor:[UIColor colorWithRed:0xf1 / 255.0 green:0x54 / 255.0 blue:0x50 / 255.0 alpha:1.0]];
}
//手指从按钮外面拖回按钮内部
- (void)moveInside:(UIButton *)speak {
    [speak setBackgroundImage:[UIImage imageNamed:@"speaking"] forState:UIControlStateNormal];
    [self.recordLabel setText:@"上滑取消"];
    [self.recordLabel setTextColor:[UIColor colorWithRed:0x27 / 255.0 green:0x88 / 255.0 blue:0xff / 255.0 alpha:1.0]];
}
//手指在按钮外面松开
- (void)speakTouchUpOutside:(UIButton *)speak {
    NSLog(@"取消录音");
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
    [speak setBackgroundImage:[UIImage imageNamed:@"speak"] forState:UIControlStateNormal];
    [self.recordLabel setText:@"按住说话"];
    [self.recordLabel setTextColor:[UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0]];
}

#pragma mark - 定位相关


- (IBAction)locationBtn:(id)sender {
//    [self sendLocationMessage];
}
#pragma mark - 图片

- (IBAction)albumBtn:(id)sender {
    //访问系统相册
    //让用户选择相册
    UIImagePickerController *imgPickerVc = [[UIImagePickerController alloc] init];
    
    // 设置代理
    imgPickerVc.delegate = self;
    
    // 设置来源
    imgPickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:imgPickerVc animated:YES completion:NULL];
}
- (IBAction)cameraBtn:(id)sender {
    //访问系统相册
    //让用户选择相册
    UIImagePickerController *imgPickerVc = [[UIImagePickerController alloc] init];
    // 设置代理
    imgPickerVc.delegate = self;
    // 设置来源为照相机
    imgPickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:imgPickerVc animated:YES completion:NULL];
}

// 用户选择图片后的回调
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    // 1.获取图片
    UIImage *selectedImg = info[UIImagePickerControllerOriginalImage];
    //对于过大的图片进行压缩
    NSData *imageData = UIImageJPEGRepresentation(selectedImg, 1);
    
    if (imageData.length > 5000000) {
        imageData = UIImageJPEGRepresentation(selectedImg, 0.1);
    }
    else if (imageData.length > 3000000) {
        imageData = UIImageJPEGRepresentation(selectedImg, 0.3);
    }
    else if (imageData.length > 1000000) {
        imageData = UIImageJPEGRepresentation(selectedImg, 0.5);
    }
    
    UIImage *newImg = [[UIImage alloc]initWithData:imageData];
    
    // 2.发送图片
    [self sendImageMessage:newImg];
    // 3.让图片选择控制器消失
    [self dismissViewControllerAnimated:YES completion:NULL];
}


- (void)dealloc {
    [WKAudioTool stopPlay];
}

@end
